import { AppDataSource } from '../config/database';
import { DeviceGroup } from '../entity/DeviceGroup';
import { Device } from '../entity/Device';

export class DeviceGroupManager {
    /**
     * 创建分组
     * @param userId
     * @param gname
     */
  async createGroup(userId: string, gname: string): Promise<DeviceGroup> {
    if (!gname || !gname.trim()) throw new Error('分组名称不能为空');

    const repo = AppDataSource.getRepository(DeviceGroup);
    const count = await repo.count({ where: { userId } });
    if (count >= 5) throw new Error('最多只能创建5个分组');

    const existing = await repo.findOne({ where: { userId, gname } });
    if (existing) throw new Error('该分组名称已存在');

    const group = repo.create({ userId, gname });
    return await repo.save(group);
  }

    /**
     * 获取分组
     * @param userId
     */
  async getGroups(userId: string) {
    const repo = AppDataSource.getRepository(DeviceGroup);
    const groups = await repo.find({ where: { userId } });

    const deviceRepo = AppDataSource.getRepository(Device);

    const result = await Promise.all(
      groups.map(async g => {
        const count = await deviceRepo.count({ where: { gid: g.gid } });
        return {
          gid: g.gid,
          gname: g.gname,
          device_count: count
        };
      })
    );

    return result;
  }

    /**
     * 删除分组
     * @param userId
     * @param gid
     */
  async deleteGroup(userId: string, gid: string): Promise<number> {
    const groupRepo = AppDataSource.getRepository(DeviceGroup);
    const deviceRepo = AppDataSource.getRepository(Device);

    const group = await groupRepo.findOne({ where: { userId, gid } });
    if (!group) throw new Error('分组不存在');

    const affected = await deviceRepo.count({ where: { gid } });

    await AppDataSource.transaction(async manager => {
      await manager.delete(DeviceGroup, { userId, gid });
      await manager.update(Device, { gid }, { gid: null });
    });

    return affected;
  }

    /**
     * 设置分组
     * @param userId
     * @param did
     * @param gid
     */
  async setGroup(userId: string, did: string, gid: string | null) {
    const deviceRepo = AppDataSource.getRepository(Device);
    const groupRepo = AppDataSource.getRepository(DeviceGroup);

    const device = await deviceRepo.findOne({ where: { did, userId } });
    if (!device) throw new Error('设备不存在');

    if (gid !== null) {
      const group = await groupRepo.findOne({ where: { userId, gid } });
      if (!group) throw new Error('分组不存在');
    }

    device.gid = gid;
    await deviceRepo.save(device);

    return { did: device.did, gid: device.gid };
  }
}
